package cn.tonyandmoney.voicenotes.notes.model

import android.text.TextUtils
import cn.tonyandmoney.voicenotes.greendao.gen.NoteRecordDao
import cn.tonyandmoney.voicenotes.greendao.gen.TNoteDao
import cn.tonyandmoney.voicenotes.greendao.gen.TRecordDao
import cn.tonyandmoney.voicenotes.greendao.utils.GreenDaoHelper
import cn.tonyandmoney.voicenotes.notes.bean.PageEntity
import cn.tonyandmoney.voicenotes.notes.entity.NoteRecord
import cn.tonyandmoney.voicenotes.notes.entity.TNote
import cn.tonyandmoney.voicenotes.notes.entity.TRecord
import org.jetbrains.anko.AnkoLogger

/**
 * 笔记持久化数据操作模型
 */
class NoteModel : AnkoLogger {

    private val mRecordDao = GreenDaoHelper.session().tRecordDao
    private val mNoteDao = GreenDaoHelper.session().tNoteDao
    private val mRecordNote = GreenDaoHelper.session().noteRecordDao


    fun addRecordNote(noteId: Long, recordId: Long) {
        mRecordNote.insert(NoteRecord(noteId, recordId))
    }

    fun addNote(note: TNote) {
        note.id = mNoteDao.insert(note)
    }


    fun addRecord(record: TRecord): Long {
        return mRecordDao.insert(record)
    }

    fun query(offset: Int, limit: Int, keywords: String?): PageEntity<TNote> {
        val entity = PageEntity<TNote>(offset, limit)
        val builder = mNoteDao.queryBuilder()
                .offset(offset)
                .limit(limit)
                .orderDesc(TNoteDao.Properties.Id)
        if (!TextUtils.isEmpty(keywords))
            builder.whereOr(TNoteDao.Properties.Name.like("%$keywords%"),
                    TNoteDao.Properties.Content.like("%$keywords%"),
                    TNoteDao.Properties.Memo.like("%$keywords%"))
        entity.total = builder.count()
        entity.page = builder.list()
        return entity
    }

    fun query(offset: Int, limit: Int, types: List<String>): PageEntity<TNote> {
        val entity = PageEntity<TNote>(offset, limit)
        val builder = mNoteDao.queryBuilder()
                .offset(offset)
                .limit(limit)
                .orderDesc(TNoteDao.Properties.Id)
        if (types.isNotEmpty())
            builder.where(TNoteDao.Properties.Type.`in`(types))
        entity.total = builder.count()
        entity.page = builder.list()
        return entity
    }

    fun loadTypes(): List<String> {
        val cursor = mNoteDao.database.rawQuery("select ${TNoteDao.Properties.Type.columnName} from" +
                " ${TNoteDao.TABLENAME} group by ${TNoteDao.Properties.Type.columnName}", arrayOf())
        val types = mutableListOf<String>()
        if (!cursor.moveToFirst()) {
            cursor.close()
            return types
        }
        while (cursor.moveToNext()) {
            types.add(cursor.getString(0))
        }
        cursor.close()
        return types
    }

    /**
     * 删除笔记及其相关数据
     */
    fun delete(note: TNote) {
        val nRecords = mRecordNote.queryBuilder()
                .where(NoteRecordDao.Properties.NoteId.eq(note.id))
                .list()
                .map { it.recordId }
        mRecordDao.queryBuilder()
                .where(TRecordDao.Properties.Id.`in`(nRecords))
                .buildDelete()
        mRecordNote.queryBuilder()
                .where(NoteRecordDao.Properties.NoteId.eq(note.id))
        mNoteDao.deleteByKey(note.id)
    }


}